import os
import subprocess
import time
import re
import shutil
from datetime import datetime
 
def ping_ips(ip_string):
    # 分割IP字符串并去除空格
    ip_list = [ip.strip() for ip in ip_string.split('|') if ip.strip()]
    
    if not ip_list:
        print("错误：未提供有效的IP地址")
        return
    
    # 获取当前日期
    current_date = datetime.now().strftime("%Y-%m-%d")
    filename = f"PING-{current_date}"
    
    # 备份已存在的文件
    if os.path.exists(filename):
        backup_filename = f"{filename}.bak"
        shutil.copy2(filename, backup_filename)
    
    # 创建/打开文件准备写入
    with open(filename, 'w', encoding='utf-8') as file:
        seq = 1  # 序列号计数器
        
        while True:
            # 获取当前时间
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            
            # 遍历所有IP地址
            for ip_address in ip_list:
                try:
                    # 执行ping命令
                    output = subprocess.check_output(
                        ['ping', '-c', '1', '-W', '1', ip_address],
                        stderr=subprocess.STDOUT,
                        universal_newlines=True
                    )
                    
                    # 解析ping输出获取延迟时间
                    time_ms = -1
                    match = re.search(r'time[=<](\d+\.?\d*)\s*ms', output)
                    if match:
                        time_ms = float(match.group(1))
                    
                    # 成功状态
                    status = "成功"
                    delay = time_ms
                    
                except subprocess.CalledProcessError:
                    # 失败状态
                    status = "失败"
                    delay = -1
                
                # 写入文件，使用|作为分隔符
                line = f"{current_time}|{seq}|{ip_address}|{delay}|{status}\n"
                print(line, end='')
                file.write(line)
                file.flush()  # 确保立即写入文件
                
                # 序列号递增
                seq += 1
            
            # 等待1秒
            time.sleep(1)
 
# 使用示例
ping_ips("47.100.42.127|202.99.160.68|8.8.8.8")